package com.googlecode.datawander.codeexecutor;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



import com.googlecode.datawander.connectors.OracleConnector;
import com.googlecode.datawander.i18n.I18n;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;

/**
 * Class to execute commands
 * @author Marcin Stachniuk
 */
public class SqlCommandExecutor {

    private static final Logger logger = Logger.getLogger(SqlCommandExecutor.class);

    public List<SqlCommand> readSqlCommands(String filename) throws SqlCommandException {
        List<SqlCommand> result = new ArrayList<SqlCommand>();
        File file = new File(filename);
        int length = (int)file.length();

        try {
            BufferedReader fileReader = new BufferedReader(
                    new FileReader(filename));

            char [] buff = new char [length];
            fileReader.read(buff);
            String text = new String(buff);
            String [] commands = text.split(";");

            for(String c : commands) {
                SqlCommand cmd = new SqlCommand();
                cmd.setCommand(c);
                result.add(cmd);
            }
        } catch(Exception e) {
            throw new SqlCommandException(e);
        }
        return result;
    }

    public void executeCommand(Connection conn, SqlCommand command) 
            throws SqlCommandException {
        executeCommand(conn, command.getCommand());
    }

    private void executeCommand(Connection conn, String command) throws SqlCommandException {
        if(command == null || command.length() == 0) {
            // empty command
            return;
        }
        try {
            PreparedStatement stmt = conn.prepareStatement(command);
            stmt.execute();
            stmt.close();

            String message = I18n.getString("oksqlcommand");
            message = String.format(message, command);
            logger.debug(message);
        } catch (Exception ex) {
            String message = I18n.getString("badsqlcommand");
            message = String.format(message, command, ex.getMessage());
            logger.debug(message, ex);
            throw new SqlCommandException(message);
        }
    }
}
